<template>
  <div v-show="visible">
    <div class="title-wrap">
      <px-button icon="ArrowLeft" type="primary" size="small" @click="closeDialog">返回 </px-button>
      <!-- <h3>{{ handleType === "Resolve" ? "处理" : "详情" }}</h3> -->
    </div>
    <div class="table-top mg-b-8">
      <px-button type="primary" plain :disabled="rowData.eventType === null" @click="handleShowEventInfo">事件处理信息</px-button>
      <px-button type="primary" plain @click="handleShowAnalysisReport">智能分析报告</px-button>
    </div>
    <div class="table-content">
      <px-descriptions border>
        <px-descriptions-item width="120" label="报警项">
          {{ tableData[0]?.energyType }}
        </px-descriptions-item>
        <px-descriptions-item width="120" label="能源">
          {{ tableData[0]?.energyName }}
        </px-descriptions-item>
        <px-descriptions-item width="120" label="监控周期">
          {{ formatPeriod(tableData[0]?.period) }}
        </px-descriptions-item>
        <px-descriptions-item width="120" label="报警时间">
          {{ tableData[0]?.alarmTime }}
        </px-descriptions-item>
        <px-descriptions-item width="120" label="报警等级">
          <span v-if="tableData[0]?.alarmLevel === null">""</span>
          <px-tag v-else type="warning">{{ formatAlarm(tableData[0]?.alarmLevel) }}</px-tag>
        </px-descriptions-item>
        <px-descriptions-item width="120" label="报警值">
          {{ tableData[0]?.alarmValue + tableData[0]?.unit }}
        </px-descriptions-item>
        <px-descriptions-item width="120" label="厂务内控值">
          {{ tableData[0]?.spcThreshold + tableData[0]?.unit }}
        </px-descriptions-item>
        <px-descriptions-item width="120" label="HSE管控值">
          {{ tableData[0]?.hseThreshold + tableData[0]?.unit }}
        </px-descriptions-item>
      </px-descriptions>
    </div>
    <div class="tab-bar">
      <CustomTabs :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
    </div>
    <div v-loading="loading" class="tab-content">
      <!-- 关联分析 -->
      <div v-if="activeName === 'related'">
        <div class="related-wrap">
          <div class="date-wrap">
            <px-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleRelatedDateChange"
            />
          </div>
          <div class="black">
            <div class="title-bar">
              {{ relatedAnalysisData?.relateAnalysisConsume?.name }}
            </div>
            <!-- <px-button class="btn-download" @click="handleExport('related')">导出</px-button> -->
            <div id="relatedChart" class="line-chart" />
          </div>
          <div class="black">
            <div class="title-bar">
              {{ relatedTemperatureLineData?.name }}
            </div>
            <!-- <px-button class="btn-download" @click="handleExport('temperature')">导出</px-button> -->
            <div id="temperatureChart" class="line-chart" />
          </div>
        </div>
      </div>
      <!-- 下钻分析 -->
      <div v-if="activeName === 'low'">
        <div class="low-top-container">
          <div class="pie-chart-container">
            <div class="title-bar">
              {{ lowAnalysisData?.pie?.title }}
            </div>
            <div class="back-wrap">
              <px-button type="primary" icon="ArrowLeft" size="small" @click="backClick">返回上一级</px-button>
            </div>
            <div id="pieChart" class="pie-chart" />
          </div>
          <div class="table-container">
            <div class="date-wrap">
              <px-date-picker
                v-model="lowQueryParams.date"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleDateChange"
              />
            </div>
            <px-table height="200" :data="lowTableData" size="small" border class="common-table table-wrap">
              <px-table-column
                v-for="item in titleData"
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
                min-width="120"
                show-overflow-tooltip
              />
            </px-table>
          </div>
        </div>
        <div class="line-container">
          <div class="title-bar">
            {{ lowAnalysisData?.multiLine?.title }}
          </div>
          <div id="multiLineChart" class="line-chart" />
          <div class="switch" @click="handleSwitch">
            <px-icon><Switch size="small" /></px-icon><span class="text">切换{{ switchType === "line" ? "堆积图" : "折线图" }}</span>
          </div>
        </div>
      </div>
      <!-- 历史报警 -->
      <div v-if="activeName === 'history'">
        <div class="history-container">
          <div class="calendar-container">
            <div class="title-bar">日历</div>
            <px-calendar v-if="tableData[0]?.period === 'D'" v-model="calendarValue" class="calendar">
              <template #header>
                <px-date-picker v-model="checkedDay" format="YYYY-MM" value-format="YYYY-MM" type="month" @change="changeCalendar" />
              </template>
              <template #date-cell="{ data }">
                <div class="calendar-day" :class="{ 'alarm-day': alarmDateList.indexOf(data.day) !== -1 }">
                  {{ data.day.split("-")[2] }}
                </div>
              </template>
            </px-calendar>
            <div v-else class="calendar">
              <div class="px-calendar__header">
                <px-date-picker v-model="checkedDay" format="YYYY" value-format="YYYY" type="year" @change="changeCalendar" />
              </div>
              <div class="month-grid">
                <div
                  v-for="month in 12"
                  :key="month"
                  :class="['month-cell', month === Number(activeMonth) ? 'selected' : '']"
                  @click="handleMonthClick(month)"
                >
                  {{ month }}月份
                </div>
              </div>
            </div>
          </div>
          <div class="table-content">
            <px-table height="530" :data="historyTableData" size="small" border class="common-table">
              <px-table-column prop="alarmTime" label="报警日期" min-width="120" show-overflow-tooltip />
              <px-table-column prop="alarmLevel" label="报警等级" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.alarmLevel === null">""</span>
                  <px-tag v-else type="warning">{{ formatAlarm(scope.row.alarmLevel) }}</px-tag>
                </template>
              </px-table-column>
              <px-table-column prop="alarmValue" label="报警值" min-width="120" show-overflow-tooltip />
            </px-table>
          </div>
        </div>
      </div>
    </div>
    <div v-if="handleType === 'Resolve'" class="footer-btn-wrap">
      <px-button v-if="rowData.eventType === null" type="danger" @click="handleCloseEvent">关闭事件</px-button>
      <px-button v-if="rowData.eventType === null" type="primary" @click="handleInitiateReforming">发起整改</px-button>
      <px-button v-if="(rowData.eventType === 'S' || rowData.eventType === 'R') && displayOperation === 1" type="primary" @click="handleReforming"
        >整改</px-button
      >
      <px-button v-if="rowData.eventType === 'M' && displayOperation === 1" type="primary" @click="handleCheck">审核</px-button>
    </div>
  </div>

  <!-- 发起整改 -->
  <px-dialog v-model="initiateReformingVisible" title="发起整改" width="700" @close="cancelInitiate">
    <px-form ref="initiateFormRef" :model="initiateFormParams" :rules="initiateFormRules" label-width="120px">
      <px-form-item label="问题说明" prop="indicator">
        <px-input v-model="initiateFormParams.indicator" type="textarea" :rows="5" maxlength="300" show-word-limit clearable />
      </px-form-item>
      <px-form-item label="整改要求" prop="ask">
        <px-input v-model="initiateFormParams.ask" type="textarea" :rows="5" maxlength="300" show-word-limit clearable />
      </px-form-item>
      <px-form-item label="整改人" prop="person">
        <px-select v-model="initiateFormParams.person" filterable clearable placeholder="请选择整改人">
          <px-option v-for="item in personList" :key="item.value" :label="item.label" :value="item.label" />
        </px-select>
      </px-form-item>
      <px-form-item label="计划完成时间" prop="planCompleteTime">
        <px-date-picker v-model="initiateFormParams.planCompleteTime" type="date" placeholder="请选择时间" value-format="YYYY-MM-DD" />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelInitiate">取消</px-button>
        <px-button type="primary" @click="saveInitiate">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <!-- 关闭事件 -->
  <px-dialog v-model="closeEventVisible" title="关闭事件" width="700" @close="cancelCloseEvent">
    <px-form ref="closeEventFormRef" :model="closeEventFormParams" :rules="closeEventFormRules" label-width="100px">
      <px-form-item label="关闭原因" prop="reason">
        <px-input v-model="closeEventFormParams.reason" type="textarea" :rows="5" maxlength="300" show-word-limit clearable />
      </px-form-item>
      <px-form-item label="上传照片" prop="pic">
        <PhotoUpload
          photoType="add"
          :photoData="{
            eventType: rowData.eventType,
            fileType: 'P',
            id: rowData.id
          }"
          :photoList="closeEventFormParams.pic"
          :countLimit="20"
          @changePhotoList="onChange"
        />
      </px-form-item>
      <px-form-item label="附件" prop="file">
        <!-- <px-button type="primary" plain @click="handleUpload">上传附件</px-button>
        <span v-if="closeEventFormParams.file">{{ closeEventFormParams.file?.name }}</span> -->
        <FileUploadComponents
          fileType="add"
          :fileData="{ moduleName: 'eqp' }"
          :fileSize="fileSize"
          :fileList="fileList"
          :multiple="multiple"
          :countLimit="countLimit"
          fileBtnText="上传文件"
          tipText="文件"
          @changeFileList="changeFileList"
        />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelCloseEvent">取消</px-button>
        <px-button type="primary" @click="saveCloseEvent">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <!-- 上传文件 -->
  <div v-if="fileUploadVisible">
    <FileUpload ref="uploadRef" v-model:visible="fileUploadVisible" @uploadAction="fileUploadConfirm" />
  </div>

  <!-- 整改 -->
  <div v-if="reformingVisible">
    <Reforming v-model:visible="reformingVisible" :rowData="rowData" @refresh="refresh" />
  </div>

  <!-- 审核 -->
  <div v-if="checkVisible">
    <Check v-model:visible="checkVisible" :rowData="rowData" @refresh="refresh" />
  </div>

  <!-- 事件处理信息 -->
  <div v-if="eventInfoVisible">
    <EventInfo v-model:visible="eventInfoVisible" :rowData="rowData" />
  </div>

  <!-- 智能分析报告 -->
  <div v-if="analysisReportVisible">
    <AnalysisReport v-model:visible="analysisReportVisible" :rowData="rowData" />
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, toRefs, computed, onMounted, getCurrentInstance } from "vue";
import * as echarts from "echarts";
import {
  getRelatedAnalysisDataAPI,
  getSpcThresholdLineAPI,
  getRelatedTemperatureLineAPI,
  getLowAnalysisDataAPI,
  getHistoryAlarmDataAPI,
  saveInitiateAPI,
  saveCloseEventAPI,
  uploadFileAPI,
  getPersonListAPI
} from "@/api/energy/monitor";
import { formatPeriod, formatAlarm } from "../utils";
import CustomTabs from "@/components/Tabs/index.vue";
import { PxMessage } from "px-ui";
import FileUpload from "./fileUpload.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import Reforming from "./reforming.vue";
import Check from "./check.vue";
import EventInfo from "./eventInfo.vue";
import AnalysisReport from "./analysisReport.vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import FileUploadComponents from "@/components/Upload/FileUpload.vue";

const router = useRouter();

const { proxy } = getCurrentInstance();

const emits = defineEmits(["update:visible", "refresh"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 区分是详情还是处理
  handleType: {
    type: String,
    default: "Resolve"
  },
  rowData: {
    type: Object,
    default() {
      return {};
    }
  },
  // 1:能耗监控, 2:负荷监控 3:损耗监控
  type: {
    type: String,
    default: "1"
  }
});

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const initiateFormRules = computed(() => ({
  indicator: [{ required: true, message: "问题说明不能为空", trigger: "blur" }],
  person: [{ required: true, message: "整改人不能为空", trigger: "change" }]
}));

const closeEventFormRules = computed(() => ({
  reason: [{ required: true, message: "关闭原因不能为空", trigger: "blur" }]
}));

const initiateFormRef = ref(null);
const closeEventFormRef = ref(null);
const uploadRef = ref(null);
const dateRange = ref([dayjs().subtract(30, "day").format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")]);

const state = reactive({
  loading: false,
  tableData: [],
  lowTableData: [],
  titleData: [],
  calendarValue: new Date(),
  historyTableData: [],
  historyTableDataCopy: [],
  alarmDateList: [],
  initiateReformingVisible: false,
  personList: [],
  initiateFormParams: {
    indicator: "",
    ask: "",
    person: ""
  },
  closeEventVisible: false,
  closeEventFormParams: {
    reason: "",
    pic: [],
    images: [],
    file: ""
  },
  lowAnalysisData: {},
  fileUploadVisible: false,
  reformingVisible: false,
  checkVisible: false,
  eventInfoVisible: false,
  analysisReportVisible: false,
  routerId: null,
  checkedDay: "",
  activeMonth: "",
  displayOperation: 0,
  lowQueryParams: {
    date: ""
  },
  relatedTemperatureLineData: {},
  relatedAnalysisData: {}
});
const {
  loading,
  tableData,
  lowTableData,
  titleData,
  calendarValue,
  historyTableData,
  alarmDateList,
  initiateReformingVisible,
  personList,
  initiateFormParams,
  closeEventVisible,
  closeEventFormParams,
  lowAnalysisData,
  fileUploadVisible,
  reformingVisible,
  checkVisible,
  eventInfoVisible,
  analysisReportVisible,
  checkedDay,
  activeMonth,
  displayOperation,
  lowQueryParams,
  relatedTemperatureLineData,
  relatedAnalysisData
} = toRefs(state);

const tabList = ref([
  { name: "related", label: "关联分析" },
  { name: "low", label: "下钻分析" },
  { name: "history", label: "历史报警" }
]);
const activeName = ref("related");

const fileList = ref([]);
const fileUploadList = ref([]);
const fileSize = ref(20);
const multiple = ref(true);
const countLimit = ref(20);
const isPieParams = ref({});
const switchType = ref("line");

let pieParamsAry = [];

const changeFileList = val => {
  fileUploadList.value = val.map(item => {
    return {
      // id: item.id,
      // originalName: item.originalName,
      // fileName: item.id,
      // fileType: item.fileType,
      // fileUrl: item.fileUrl,
      // accountId: item.accountId,
      // accountName: item.accountName,
      // status: item.status,
      // createTime: item.createTime,
      // updateTime: item.updateTime,
      alarmId: props.rowData.id,
      name: item.originalName,
      fileKey: item.fileUrl,
      fileSize: item.fileSize,
      fileType: "A",
      extension: item.fileType
    };
  });
};
onMounted(() => {
  const { id } = router.currentRoute.value.query;
  state.routerId = id;
  state.tableData = [props.rowData];
  if (tableData.value[0]?.period === "D") {
    state.checkedDay = dayjs().format("YYYY-MM");
  } else {
    state.checkedDay = dayjs().format("YYYY");
    state.activeMonth = dayjs().format("M");
  }
  getRelatedData();
});

const onChange = val => {
  state.closeEventFormParams.images = val
    .map(item => {
      const data = item?.response?.data;
      return data
        ? {
            alarmId: state.routerId ?? props.rowData.id,
            name: data.originalName,
            fileKey: data.fileUrl,
            fileSize: data.fileSize,
            fileType: "P",
            extension: data.fileType
          }
        : null;
    })
    .filter(item => !!item);
};
// 切换tab
const handelTabSelected = val => {
  activeName.value = val;
  pieParamsAry = [];
  if (val === "related") {
    getRelatedData();
  } else if (val === "low") {
    getLowAnalysis();
  } else if (val === "history") {
    getHistoryAlarmData();
  }
};
// 新的---关联分析
const getRelatedData = async () => {
  try {
    state.loading = true;
    const res = await Promise.all([getAnalysisData(), getSpcThresholdLine(), getRelatedTemperatureLine()]);
    let data = res[0]?.relateAnalysisConsume?.data || {};
    let obj = {
      xAxisData: data.category || [],
      seriesData: data.value || [],
      // title: data.name,
      markLine: {
        symbol: ["none", "none"],
        data: [
          {
            yAxis: res[1]?.yhseDataAxis[0] || 0,
            lineStyle: {
              color: "red",
              type: "dashed"
            },
            label: {
              position: "end"
              // formatter: `${res[1]?.yhseDataAxis[0]}`
            }
          },
          {
            yAxis: res[1]?.yspcDataAxis[0] || 0,
            lineStyle: {
              color: "red",
              type: "dashed"
            },
            label: {
              position: "end"
              // formatter: `${res[1]?.yspcDataAxis[0]}`
            }
          }
        ]
      },
      labelUnit: res[0]?.relateAnalysisConsume?.labelUnit
    };
    data ? newDrawLineChart(obj, "relatedChart") : "";
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 消耗量的数据
const getAnalysisData = async () => {
  try {
    const params = {
      id: state.routerId ?? props.rowData.id,
      startDate: dateRange.value[0] + " 00:00:00" || "",
      endDate: dateRange.value[1] + " 23:59:59" || ""
    };
    const res = await getRelatedAnalysisDataAPI(params);
    if (res) {
      displayOperation.value = res.displayOperation;
      res.alarmValue = formatToThousands(res.alarmValue);
      res.hseThreshold = formatToThousands(res.hseThreshold);
      res.spcThreshold = formatToThousands(res.spcThreshold);
      state.tableData = [res];
      state.relatedAnalysisData = res;
    }
    let deepStartTime = dayjs(res?.alarmTime).subtract(30, "day").format("YYYY-MM-DD") || "";
    let deepEndTime = dayjs(res?.alarmTime).format("YYYY-MM-DD") || "";
    state.lowQueryParams.date = [deepStartTime, deepEndTime];
    return res;
  } catch (error) {
    console.log(error);
  }
};
// 消耗量的基准线
const getSpcThresholdLine = async () => {
  try {
    const params = {
      id: state.routerId ?? props.rowData.id,
      startDate: dateRange.value[0] + " 00:00:00" || "",
      endDate: dateRange.value[1] + " 23:59:59" || ""
    };
    const res = await getSpcThresholdLineAPI(params);
    return res;
  } catch (error) {
    console.log(error);
  }
};
// 温度的数据
const getRelatedTemperatureLine = async () => {
  try {
    const params = {
      id: state.routerId ?? props.rowData.id,
      startDate: dateRange.value[0] + " 00:00:00" || "",
      endDate: dateRange.value[1] + " 23:59:59" || ""
    };
    const res = await getRelatedTemperatureLineAPI(params);
    state.relatedTemperatureLineData = res;
    if (res) {
      let obj = {
        xAxisData: res.xdateAxis || [],
        seriesData: res.ytempAverageAxis || []
        // title: res.name
      };
      newDrawLineChart(obj, "temperatureChart");
    }
  } catch (error) {
    console.log(error);
  }
};

// 日期改变
const handleRelatedDateChange = () => {
  getRelatedData();
};

// 导出
const handleExport = val => {
  const params = {
    id: state.routerId ?? props.rowData.id,
    startDate: dateRange.value[0] + " 00:00:00" || "",
    endDate: dateRange.value[1] + " 23:59:59" || ""
  };
  if (val === "related") {
    proxy.download("post", "/energy/consumptionMonitor/exportRelateLossLine", params, `关联分析-消耗量.xlsx`);
  } else {
    proxy.download("post", "/energy/consumptionMonitor/exportTemperatureLine", params, `关联分析-温度.xlsx`);
  }
};

const propAry = ["name", "value", "proportion", "yoy", "qoq", "date"];
// 下钻分析
const getLowAnalysis = async () => {
  try {
    state.loading = true;
    let deepStartTime = state.lowQueryParams.date[0] + " 23:59:59" || "";
    let deepEndTime = state.lowQueryParams.date[1] + " 00:00:00" || "";
    let type = props.type;
    const params = {
      id: state.routerId ?? props.rowData.id,
      deepStartTime: deepStartTime,
      deepEndTime: deepEndTime,
      monitorType: Number(type)
    };
    const res = await getLowAnalysisDataAPI(params);
    state.lowAnalysisData = res;
    state.lowTableData = res?.table?.content;
    let titleAry = res?.table?.title?.filter(item => item !== "日期") || [];
    state.titleData = titleAry.map((i, idx) => {
      return {
        label: i,
        prop: propAry[idx]
      };
    });
    res.pie ? drawPieChart(res.pie) : "";
    res.multiLine ? drawMultiLineChart(res.multiLine) : "";
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};
// 点击下钻分析的饼图，调用接口
const getLowData = async args => {
  try {
    state.loading = true;
    let deepStartTime = state.lowQueryParams.date[0] + " 23:59:59" || "";
    let deepEndTime = state.lowQueryParams.date[1] + " 00:00:00" || "";
    const params = {
      id: props.rowData.id || "",
      pieId: args?.labelId || "",
      typeValue: args?.typeValue || "",
      deepStartTime: deepStartTime,
      deepEndTime: deepEndTime
    };
    const res = await getLowAnalysisDataAPI(params);
    state.lowAnalysisData = res;
    state.lowTableData = res?.table?.content;
    res.pie ? drawPieChart(res.pie) : "";
    res.multiLine ? drawMultiLineChart(res.multiLine) : "";
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

// 历史报警
const getHistoryAlarmData = async () => {
  try {
    state.loading = true;
    const params = {
      id: state.routerId ?? props.rowData.id
    };
    const res = await getHistoryAlarmDataAPI(params);
    state.alarmDateList = res.data.map(item => item.alarmTime);
    state.historyTableDataCopy = JSON.parse(JSON.stringify(res.data));
    let time = state.checkedDay;
    filterHistoryTableData(time);
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};
/**
 * 将数字字符串转换为千分位格式
 * @param {string} numStr - 带两位小数的字符串（如 "12345.67"）
 * @returns {string} - 千分位格式字符串（如 "12,345.67"）
 */
const formatToThousands = stringNumber => {
  // 确保输入是字符串
  const str = String(stringNumber);

  // 分离整数部分和小数部分
  const parts = str.split(".");
  const integerPart = parts[0];
  const decimalPart = parts.length > 1 ? "." + parts[1] : "";

  // 使用正则表达式添加千分位分隔符
  const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

  // 返回拼接后的结果
  return formattedInteger + decimalPart;
};

// 过滤历史报警信息
// args1: YYYY-MM,YYYY,MM,
const filterHistoryTableData = args => {
  let period = state.tableData[0]?.period;
  // D：每日
  // M：每月
  let searchYear = "";
  let searchMonth = "";
  if (String(args)?.includes("-")) {
    let ary = args?.split("-");
    searchYear = ary[0];
    searchMonth = ary[1];
  } else {
    searchYear = state.checkedDay;
    searchMonth = state.activeMonth > 10 ? state.activeMonth : "0" + String(state.activeMonth);
  }

  state.historyTableData = state.historyTableDataCopy.filter(item => {
    item.alarmValue = formatToThousands(item.alarmValue);
    let [year, month] = item.alarmTime?.split("-");
    if (period === "D" && searchMonth === month) {
      return item;
    }
    if (period === "M" && searchYear === year && searchMonth === month) {
      return item;
    }
  });
};
const changeCalendar = val => {
  state.calendarValue = new Date(val);
  filterHistoryTableData(val);
};
const handleMonthClick = val => {
  state.activeMonth = val;
  filterHistoryTableData(val);
};
const newDrawLineChart = (obj, dom) => {
  let myChart = echarts.init(document.getElementById(dom));
  let series = [];
  if (obj?.markLine) {
    series = [
      {
        data: obj?.seriesData || [],
        type: "line",
        markLine: obj?.markLine
      }
    ];
  } else {
    series = [
      {
        data: obj?.seriesData || [],
        type: "line"
      }
    ];
  }
  let option = {
    title: {
      text: obj?.title || ""
    },
    toolbox: {
      show: true,
      top: 3,
      feature: {
        saveAsImage: {
          title: "点击保存为图片"
        }
      }
    },
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "10%",
      right: "10%",
      top: "35%",
      bottom: "10%"
    },
    xAxis: {
      type: "category",
      data: obj?.xAxisData || []
    },
    yAxis: {
      type: "value",
      name: obj?.labelUnit || "°C",
      axisLabel: {
        formatter: function (value) {
          if (value >= 1e12) {
            return (value / 1e12).toFixed(1) + "T"; // 万亿
          } else if (value >= 1e9) {
            return (value / 1e9).toFixed(1) + "B"; // 十亿
          } else if (value >= 1e6) {
            return (value / 1e6).toFixed(1) + "M"; // 百万
          } else if (value >= 1e3) {
            return (value / 1e3).toFixed(1) + "K"; // 千
          }
          return value;
        }
      }
    },
    series: series
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

const drawLineChart = (item, dom) => {
  let myChart = echarts.init(document.getElementById(dom));
  let option = {
    grid: {
      left: "5%",
      right: 16,
      top: 16,
      bottom: "10%"
    },
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      show: true,
      type: "category",
      data: item?.category || []
    },
    yAxis: {
      show: true,
      type: "value",
      name: item?.name || "",
      axisLabel: {
        formatter: function (value) {
          if (value >= 1e12) {
            return (value / 1e12).toFixed(1) + "T"; // 万亿
          } else if (value >= 1e9) {
            return (value / 1e9).toFixed(1) + "B"; // 十亿
          } else if (value >= 1e6) {
            return (value / 1e6).toFixed(1) + "M"; // 百万
          } else if (value >= 1e3) {
            return (value / 1e3).toFixed(1) + "K"; // 千
          }
          return value;
        }
      }
    },
    series: [
      {
        name: item?.categoryName[0]?.name || "",
        data: item?.value[0] || [],
        type: "line",
        tooltip: {
          valueFormatter: function (value) {
            return value + " " + item?.categoryName[0]?.unit;
          }
        }
      },
      {
        name: item?.categoryName[1]?.name || "",
        data: item.value[1] || [],
        type: "line",
        tooltip: {
          valueFormatter: function (value) {
            return value + " " + item?.categoryName[1]?.unit;
          }
        }
      }
    ]
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

const drawPieChart = data => {
  let myChart = echarts.init(document.getElementById("pieChart"));
  let option = {
    tooltip: {
      trigger: "item"
    },
    legend: {
      type: "scroll",
      orient: "vertical",
      left: "5%",
      top: "middle"
    },
    series: [
      {
        name: "子系统占比",
        type: "pie",
        radius: "50%",
        data: data.data,
        center: ["60%", "50%"],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  };
  nextTick(() => {
    myChart.setOption(option);
    myChart.on("click", args => {
      let params = args?.data || {};
      // 不是叶子节点，可以进行点击。
      // leafFlag：'0'，非叶子节点
      // leafFlag：'1', 叶子节点
      if (params?.leafFlag === "0") {
        isPieParams.value = params;
        pieParamsAry.push(params);
        getLowData(params);
      }
    });
  });
};

const drawMultiLineChart = data => {
  let obj = data?.data || {};
  let myChart = echarts.init(document.getElementById("multiLineChart"));
  let seriesData = obj?.lineCategoryName?.map((i, idx) => {
    return {
      name: i?.name || "",
      data: obj?.value[idx] || [],
      type: switchType.value,
      stack: "Total",
      tooltip: {
        valueFormatter: function (value) {
          return value + " " + i.unit;
        }
      }
    };
  });
  let option = {
    grid: {
      left: "10%",
      right: 16,
      top: 16,
      bottom: "10%"
    },
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      show: true,
      type: "category",
      data: obj.category || []
    },
    yAxis: {
      show: true,
      type: "value",
      name: data.labelUnit,
      axisLabel: {
        formatter: function (value) {
          if (value >= 1e12) {
            return (value / 1e12).toFixed(1) + "T"; // 万亿
          } else if (value >= 1e9) {
            return (value / 1e9).toFixed(1) + "B"; // 十亿
          } else if (value >= 1e6) {
            return (value / 1e6).toFixed(1) + "M"; // 百万
          } else if (value >= 1e3) {
            return (value / 1e3).toFixed(1) + "K"; // 千
          }
          return value;
        }
      }
    },
    series: seriesData
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

const closeDialog = () => {
  emits("update:visible", false);
};

// 事件处理信息
const handleShowEventInfo = () => {
  state.eventInfoVisible = true;
};

// 关闭事件
const handleCloseEvent = () => {
  state.closeEventVisible = true;
};

const fileUploadConfirm = async fileList => {
  let formData = new FormData();
  formData.append("id", props.rowData.id);
  formData.append("eventType", props.rowData.eventType);
  formData.append("fileType", "A");
  formData.append("file", fileList[0].raw);
  const data = await uploadFileAPI(formData);
  state.closeEventFormParams.file = {
    alarmId: state.routerId ?? props.rowData.id,
    name: data.fileName,
    fileKey: data.fileUrl,
    fileSize: data.fileSize,
    fileType: "A",
    extension: data.fileType
  };
  state.fileUploadVisible = false;
  PxMessage.success("上传成功");
};

// 取消关闭事件
const cancelCloseEvent = () => {
  state.closeEventVisible = false;
};

// 保存关闭事件
const saveCloseEvent = () => {
  closeEventFormRef.value.validate(async validate => {
    if (validate) {
      // const { reason, pic, file } = state.closeEventFormParams;
      const { reason, images } = state.closeEventFormParams;
      const params = {
        id: props.rowData.id,
        opinion: reason,
        images: images,
        // files: [file],
        files: fileUploadList.value ? fileUploadList.value : undefined
      };
      await saveCloseEventAPI(params);
      state.closeEventVisible = false;
      emits("refresh");
      PxMessage.success("关闭成功");
    }
  });
};

const getPersonList = async () => {
  try {
    const res = await getPersonListAPI();
    if (res?.data?.length) {
      let data = res?.data;
      data.forEach(item => {
        item.id = item.userId;
        item.label = `${item.userId}-${item.username}-${item.realName}`;
        item.value = item.userId;
      });
      state.personList = data;
    } else {
      state.personList = [];
    }
  } catch (error) {
    console.log(error);
  }
};

// 发起整改
const handleInitiateReforming = () => {
  state.initiateReformingVisible = true;
  getPersonList();
};

// 取消发起整改
const cancelInitiate = () => {
  initiateFormRef.value.resetFields();
  state.initiateReformingVisible = false;
};

// 确认发起整改
const saveInitiate = () => {
  initiateFormRef.value.validate(async validate => {
    if (validate) {
      const { indicator, ask, person, planCompleteTime } = state.initiateFormParams;
      const params = {
        id: props.rowData.id,
        questionState: indicator,
        opinion: ask,
        handlerId: person,
        planCompleteTime
      };
      await saveInitiateAPI(params);
      state.initiateReformingVisible = false;
      emits("refresh");
      PxMessage.success("发起整改成功");
    }
  });
};

// 整改
const handleReforming = () => {
  state.reformingVisible = true;
};

// 审核
const handleCheck = () => {
  state.checkVisible = true;
};

// 智能分析报告
const handleShowAnalysisReport = () => {
  state.analysisReportVisible = true;
};

const refresh = () => {
  emits("refresh");
};

const handleDateChange = () => {
  if (Object.keys(isPieParams.value)) {
    getLowData(isPieParams.value);
  } else {
    getLowAnalysis();
  }
};

const handleSwitch = () => {
  if (switchType.value === "bar") {
    switchType.value = "line";
  } else {
    switchType.value = "bar";
  }
  state.lowAnalysisData.multiLine ? drawMultiLineChart(state.lowAnalysisData?.multiLine) : "";
};

const backClick = () => {
  if (!pieParamsAry.length) {
    getLowAnalysis();
  } else {
    pieParamsAry = [...new Map(pieParamsAry.map(item => [item.labelId, item])).values()];
    pieParamsAry.pop();
    let obj = pieParamsAry.pop();
    getLowData(obj);
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/common/energy/monitor/monitorEvent/scss/common.scss");

.footer-btn-wrap {
  text-align: right;
}

.title-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  h3 {
    margin-left: 10px;
  }
}

.chart-container {
  width: 100%;
  height: 270px;
}

.chart-bar {
  width: 100%;
  margin-bottom: 16px;
  border: 1px solid #dfdfdf;
}

.title-bar {
  width: 100%;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  line-height: 36px;
  color: #000;
  text-align: center;
  background: #e7eefb;
  border-bottom: 1px solid #dfdfdf;
}

.pie-chart-container {
  position: relative;
  width: 667px;
  margin-right: 16px;
  border: 1px solid #dfdfdf;

  .back-wrap {
    position: absolute;
    top: 5px;
    right: 5px;
  }
}

.line-container {
  width: 100%;
  margin: 10px 0;
  border: 1px solid #dfdfdf;

  .switch {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 5px;
    cursor: pointer;

    .text {
      font-size: 12px;
    }
  }
}

.calendar-container {
  width: 500px;
  height: 537px;
  margin-right: 16px;
  border: 1px solid #dfdfdf;

  .calendar {
    width: 100%;
    height: 495px;

    .month-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
      padding: 20px;
      border-top: 1px solid #dfdfdf;

      .month-cell {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 80px;
        cursor: pointer;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        transition: all 0.2s;
      }

      .month-cell:hover {
        background-color: #f5f7fa;
        border-color: #409eff;
      }

      .month-cell.selected {
        color: white;
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }
}

.pie-chart {
  width: 100%;
  height: 200px;
  margin-right: 16px;
}

.related-wrap {
  display: flex;
  flex-direction: column;

  .date-wrap {
    position: relative;
    text-align: right;
  }

  .line-chart {
    height: 250px;
  }

  .title-bar {
    position: absolute;
  }

  .black {
    position: relative;
    margin-top: 8px;
    border: 1px solid #dfdfdf;

    .btn-download {
      position: absolute;
      top: 10px;
      right: 30px;
    }
  }
}

.low-top-container {
  display: flex;

  .date-wrap {
    margin-bottom: 8px;
  }
}

.history-container {
  display: flex;
  align-items: center;
}

.table-container,
.table-content {
  flex: 1;
}

.line-chart {
  width: 100%;
  height: 285px;
}

.calendar-day {
  width: 100%;
  height: 100%;
  padding: 8px;
}

.alarm-day {
  color: #fff;
  background: #ef4444;
}

:deep(.px-calendar-table .px-calendar-day) {
  height: 55px;
  padding: 0;
}

:deep(.px-calendar__button-group) {
  display: none;
}
</style>
